using System;

namespace SharpMud.Net.Telnet.Session.DataProcessors.IAC
{
	public class IACTelnetLayer
	{
		#region Private Variables
		private SharpMud.Net.Telnet.Session.TelnetSessionBase	_HostSession;
		private IAC.OutputLayer											_Out;
		private IAC.InputLayer											_In;
		#endregion

		#region Constructors
		public IACTelnetLayer(SharpMud.Net.Telnet.Session.TelnetSessionBase hostSession)
		{
			_HostSession = hostSession;
			_In = new InputLayer(this);
			_Out = new OutputLayer(this);
		}
		#endregion

		#region Public Properties
		public IAC.InputLayer In
		{
			get
			{
				return _In;
			}
		}

		public IAC.OutputLayer Out
		{
			get
			{
				return _Out;
			}
		}

		public SharpMud.Net.Telnet.Session.TelnetSessionBase	HostSession
		{
			get
			{
				return _HostSession;
			}
		}
		#endregion

		#region Static Util Stuff
		public static byte[] EscapeIAC(byte[] unescapedData)
		{
			System.Collections.IQueue<byte> bq = new System.Collections.GenericQueue<byte>();
			foreach(byte b in unescapedData)
			{
				if(b==(byte)255)
				{
					bq.Enqueue((byte)255);
					bq.Enqueue((byte)255);
				}
				else
				{
					bq.Enqueue(b);
				}
			}
			return bq.ToArray();
		}
		public static byte[] UnescapeIAC(byte[] escapedData)
		{
            System.Collections.Generic.List<byte> returnBytes = new System.Collections.Generic.List<byte>();
            for (int x = 0; x < escapedData.Length; x++)
            {
                if (escapedData[x] == 255)
                {
                    if (x < (escapedData.Length - 1))
                    {
                        if (escapedData[x + 1] == 255)
                        {
                            returnBytes.Add(escapedData[x]);
                            x++;
                        }
                        else
                        {
                            //Grr! We shouldn't get here.
                            System.Diagnostics.Debugger.Break();
                        }
                    }
                }
                else
                {
                    returnBytes.Add(escapedData[x]);        
                }
                return returnBytes.ToArray();
            }
			System.Text.Encoding e = System.Text.Encoding.Default;
			string s = e.GetString(escapedData);
			s = s.Replace(System.Convert.ToChar(
				(byte)255).ToString() + System.Convert.ToChar((byte)255).ToString(),
				System.Convert.ToChar((byte)255).ToString()
				);
			return e.GetBytes(s);
		}
		#endregion
	}
}
